package com.lm.bytebuddy.example;

import com.lm.bytebuddy.ele.GreetingHandler;
import com.lm.bytebuddy.inter.Greeting;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;

import static net.bytebuddy.matcher.ElementMatchers.named;

public class DynamicProxyExample {
    public static void main(String[] args) throws Exception {
        // 动态生成代理类
        Class<?> proxyClass = new ByteBuddy()
                .subclass(Object.class)
                .implement(Greeting.class) // 实现接口
                .method(named("greet")) // 匹配接口方法
                .intercept(InvocationHandlerAdapter.of(new GreetingHandler())) // 拦截方法调用
                .make()
                .load(DynamicProxyExample.class.getClassLoader())
                .getLoaded();

        // 实例化代理类并调用方法
        Greeting greeting = (Greeting) proxyClass.getConstructor().newInstance();
        System.out.println(greeting.greet("ByteBuddy")); // 输出：Hello, ByteBuddy!
    }
}
